package com.yao.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yao.dataobject.OrderDetail;
import com.yao.dto.OrderDTO;
import com.yao.enums.ResultEnum;
import com.yao.exception.WeixinSellException;
import com.yao.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * User: 姚宏武
 * Date: 2017/11/20
 * Time: 13:28
 * Email：401369870@qq.com
 * Description: 对象转换器
 */
@Slf4j
public class OrderForm2OrderDTOConverter {

    /**
     * 将OrderForm对象转成OrderDTO对象
     *
     * @param orderForm
     * @return
     */
    public static OrderDTO convert(OrderForm orderForm) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetail> orderDetailList = new ArrayList<>();
        Gson gson = new Gson();
        try {
            orderDetailList = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>() {
                    }.getType());
        }catch (Exception e){
            log.error("【对象转换】错误，string={}",orderForm.getItems());
            throw new WeixinSellException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

}
